import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { createQueryBuilder, Repository } from 'typeorm';
import { TagDto } from './dto/tag.dto';
import { Tag } from './tag.entity';

@Injectable()
export class TagService {
    constructor(
        @InjectRepository(Tag)
        private readonly tagRepo: Repository<Tag>,
    ) { }

    // 新增文章标签
    async saveTag(newTag: TagDto) {
        return await this.tagRepo.save(newTag)
    }

    // 查询所有文章标签
    async getAllTag() {
        return await this.tagRepo.find()
    }

    // 根据id查询文章标签
    async getTagById(id: number) {
        return await this.tagRepo.findOne(id)
    }

    // 更新文章标签
    async updateTagById(id: number, updatedTag: TagDto) {
        return await this.tagRepo.update(id, updatedTag)
    }

    // 删除文章标签
    async deleteTagById(id: number) {
        return await this.tagRepo.delete(id)
    }

    // 分页返回数据 包括 totalnum 、pagenum、tags
    async getTagByQuery(query, pagenum, pagesize) {
        // 总数
        // let total = await this.tagRepo
        // .createQueryBuilder('tag')
        // .getCount()


        let keyWord = { key: `%${query}%` }
        let sql1 = query ? 'tag.name like :key' : "1=1"

        let tags = await this.tagRepo
            .createQueryBuilder('tag')
            //.where("tag.name like :name", {name: `%${query}%`})
            .where(sql1, keyWord)
            .skip((pagenum - 1) * pagesize)
            .take(pagesize)
            .getManyAndCount()
        // console.log(tags)
        let total = tags[1]
        // 整理结果
        let result = {
            total: total,
            pagenum: pagenum,
            tags: tags[0]
        }

        return result
    }

    // 批量插入标签
    async insertManyTags(newTags: TagDto[]) {
        try {
            let insertContent = []
            newTags.forEach(v => {
                let tmp = {}
                tmp['name'] = v
                insertContent.push(tmp)
            })
            const res = await createQueryBuilder()
                .insert()
                .into(Tag)
                .values(insertContent)
                .execute()
            return res
        } catch (e) {
            console.log(e)
        }
    }

    // 批量查询
    async getTagsByIds(ids: number[]){
        return await this.tagRepo.findByIds(ids)
    }

}
